package com.szbmyoubao.app.ui.login.register

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import com.szbmyoubao.app.timer.tickFlow
import com.szbmyoubao.app.ui.webview.WebHelper
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.load
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.ActivityRegisterBinding
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2023/4/13 16:09
 * @des
 */
class RegisterActivity : BaseMvvmActivity<ActivityRegisterBinding, RegisterViewModel>(),
    View.OnClickListener {
    override val userBaseTitle: Boolean
        get() = false

    // (属性) 用于取消，确保不会重复收集流
    private var mTickJob: Job? = null

    companion object {
        fun launch(context: Context) {
            context.startActivity(Intent(context, RegisterActivity::class.java))
        }
    }

    override fun inflateBinding(): ActivityRegisterBinding =
        ActivityRegisterBinding.inflate(layoutInflater)

    override fun initialize(savedInstanceState: Bundle?) {
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is RegisterState.Checked -> {
                    setCheckRes(it.checked)
                }
                is RegisterState.SmdCodeSuccess -> {
                    ToastUtils.show("验证码已发送")
                    countDown()
                }
                is RegisterState.RegisterSuccess -> {
                    ToastUtils.show("注册成功")
                    finish()
                }
                is RegisterState.GetPicCodeSuccess -> {
                    logD("图片验证码:${it.url}")
                    binding.ivPicCode.load(this, it.url)
                }
                else -> {}
            }
        }
    }

    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(true)
            titleBar(binding.toolBar)
        }
    }

    override val darkFont: Boolean
        get() = false

    override fun initEvent() {
        binding.ivEye.setOnClickListener(this)
        binding.ivReEye.setOnClickListener(this)
        binding.tvSendTitle.setOnClickListener(this)
        binding.tvConfirm.setOnClickListener(this)
        binding.toolBar.setNavigationOnClickListener { finish() }
        binding.etPhone.addTextChangedListener(textWatch)
        binding.ivPicCode.setOnClickListener(this)
        binding.tvUserAgreement.setOnClickListener(this)
        binding.tvPrivateAgreement.setOnClickListener(this)
        binding.ivCheck.setOnClickListener(this)
    }

    private val textWatch = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            if (!s.isNullOrEmpty() && s.toString().length == 11) {
                binding.layoutPicCode.visibility = View.VISIBLE
                lifecycleScope.launch {
                    viewModel.intentChannel.send(RegisterIntent.GetPicCode(s.toString()))
                }
            } else {
                binding.layoutPicCode.visibility = View.GONE
            }
        }

    }

    override fun initData() {
    }
    private fun setCheckRes(checked: Boolean) {
        binding.ivCheck.setImageResource(if (checked) R.mipmap.icon_check_select else R.mipmap.icon_check_unselect)
    }
    /**
     * 密码是否可见
     * 1 明文
     */
    private fun setEysSee(editText: EditText, imageView: ImageView) {
        logD("type=${editText.inputType}")
        if (editText.inputType == 1) {
            editText.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
        } else {
            editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL
        }
        setSye(imageView, editText.inputType == 1)
        //光标位置
        editText.setSelection(editText.text.toString().length)
    }

    private fun setSye(imageView: ImageView, isSee: Boolean) {
        imageView.setImageResource(if (isSee) R.mipmap.icon_eye_open else R.mipmap.icon_eye_close)
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.iv_check -> {
                lifecycleScope.launch {
                    viewModel.intentChannel.send(RegisterIntent.ChangeCheck)
                }
            }
            R.id.iv_eye -> {
                setEysSee(binding.etPassword, binding.ivEye)
            }
            R.id.iv_re_eye -> {
                setEysSee(binding.etRePassword, binding.ivReEye)
            }
            R.id.tv_send_title -> {
                val phone = binding.etPhone.text.toString().trim()
                val imagCode = binding.etPicCode.text.toString().trim()
                lifecycleScope.launch {
                    viewModel.intentChannel.send(RegisterIntent.SendSmsCode(imagCode, phone))
                }
            }
            R.id.tv_confirm -> {
                toRegister()
            }
            R.id.iv_pic_code -> {
                val phone = binding.etPhone.text.toString().trim()
                lifecycleScope.launch {
                    viewModel.intentChannel.send(RegisterIntent.GetPicCode(phone))
                }
            }
            binding.tvUserAgreement.id -> {
                WebHelper.Companion.toUserAgreement(this)
            }

            binding.tvPrivateAgreement.id -> {
                WebHelper.Companion.toPrivateAgreement(this)
            }
        }
    }

    private fun toRegister() {
        val phone = binding.etPhone.text.toString().trim()
        val psw = binding.etPassword.text.toString().trim()
        val rePsw = binding.etRePassword.text.toString().trim()
        val code = binding.etSmsCode.text.toString().trim()

        lifecycleScope.launch {
            viewModel.intentChannel.send(RegisterIntent.Register(code, psw, rePsw, phone, null))
        }
    }


    // (函数)，开始倒计时
    private fun countDown() {
        var duration = 60
        mTickJob?.cancel()
        mTickJob = tickFlow {
            duration -= 1
            if (duration <= 0) {
                mTickJob?.cancel()
                // 结束
                binding.tvSendTitle.text = "发送验证码"
                binding.tvSendTitle.isEnabled = true
            } else {
                binding.tvSendTitle.text = "${duration}后重发"
                binding.tvSendTitle.isEnabled = false
            }
        }
    }

    override fun onDestroy() {
        binding.etPhone.removeTextChangedListener(textWatch)
        super.onDestroy()
    }
}